load "ct_raid_importer.rb"

class RaidsController < ApplicationController
  scaffold :raid
  layout "standard-layout"
  
  def import
    @name = params[:name]
    
  end
  
  #def destroy
  #  render_text "Switched off for now to prevent 'accidents' :) "
  #end
  
  def newdrop
    @raid = Raid.find(params[:id])
    @itemlist = []
    @eventlist = []
    @characterlist = []
    items = Item.find(:all)
    
    items.each do |i|
      @itemlist << [ i.name, i.id ]
    end
    @raid.attendances.each do |a|
      @characterlist << [ a.character.name, a.character.id]
    end
    @raid.raid_events.each do |re|
      @eventlist << [ re.event.name, re.id ] 
    end
    @eventlist << [ "None", nil ] #only need this once :)
  end
 
  def adddrop
    @raid = Raid.find(params[:id])
    @drop = ItemDrop.new(@params['drop'])
    @drop.raid = @raid
    @drop.save
    redirect_to :action => 'show', :id => params[:id]
  end

   def newattendance
    @raid = Raid.find(params[:id])
    @characters = Character.find(:all)
    @characters.each do |c|
      @characterlist << [ c.name, c.id]
    end
  end
  
  def addattendance
    @raid = Raid.find(params[:id])
    @attendance = Attedance.new(@params['attendance'])
    @attendance.raid = @raid
    @attendance.save
    redirect_to :action => 'show', :id => params[:id]
  end

  def parse    
      
    text = params[:parse_xml].to_s

    #TODO: implement graceful error handling
    #(Gaff is going to kill me for this)
    
    @raid = Raid.new
    @raid.name = params[:name].to_s
    @importer = CtRaidImporter.new(@raid)
    
    @importer.import!(text)
    
    @raid.raid_events.each do |raid_event|
      raid_event.event.parent_id = Event.find_by_parent_id(nil).id
      raid_event.event.save
    end
    
    @raid.generate_attendance

    flash[:notice] = 'Raid was successfully updated.'
    redirect_to :action => 'show', :id => @raid
  end
end
